package com.chinasofti.framework.dataaccess;

import java.io.InputStream;
import java.util.ArrayList;

import android.content.Context;

import com.chinasofti.framework.data.Entity;
import com.chinasofti.framework.net.ResponseDataCategory;
import com.chinasofti.framework.parser.XmlParser;

public abstract class AssetsDataAccess<T extends Entity> implements IReadDataAccess<T> {
	
	private Context m_context;
	private XmlParser<T> m_parser;

	protected abstract String getAssetsPath();
	
	public AssetsDataAccess(Context context) {
		m_context = context;
	}
	
	public AssetsDataAccess() {
		
	}
	
	protected Context getContext() {
		return m_context;
	}
	
	public void init(Context context) {
		m_context = context;
		m_parser = getParser();
	}

	@Override
	public void loadAll(ArrayList<T> outEntities) throws Exception {
		InputStream inputStream = getContext().getAssets().open(getAssetsPath());
		m_parser.DoParse(inputStream, outEntities);
	}

	@Override
	public void load(Object key, T outEntity) throws Exception {
		ArrayList<T> entities = new ArrayList<T>();
		loadAll(entities);
		if(entities.size() == 0) {
			outEntity = null;
		}
		
		for(int i = 0; i < entities.size(); i++) {
			T entity = entities.get(i);
			if(entity.getKey().equals(key)) {
				outEntity = entity;
				break;
			}
		}
	}

	@Override
	public void load(Filter filter, ArrayList<T> outEntities) throws Exception {
		ArrayList<T> entities = new ArrayList<T>();
		loadAll(entities);
		DataAccessUtils.find(entities, filter, outEntities);
	}
	
	@Override
	public long loadAll(long from, long to, ArrayList<T> outEntities,
			ArrayList<ResponseDataCategory> outCategories) throws Exception {
		ArrayList<T> entities = new ArrayList<T>();
		loadAll(entities);
		for(int i = 0; i >= from && i < to && i < entities.size(); i++ ) {
			outEntities.add(entities.get(i));
		}
		return entities.size();
	}

	@Override
	public long load(Filter filter, long from, long to, ArrayList<T> outEntities,
			ArrayList<ResponseDataCategory> outCategories) throws Exception {
		ArrayList<T> entities = new ArrayList<T>();
		load(filter, entities);
		for(int i = 0; i >= from && i < to && i < entities.size(); i++ ) {
			outEntities.add(entities.get(i));
		}
		return entities.size();
	}
	
	@Override
	public long load(ArrayList<Parameter> params, long from, long to,
			ArrayList<T> outEntities,
			ArrayList<ResponseDataCategory> categories) throws Exception {
		ArrayList<T> entities = new ArrayList<T>();
		load(params, entities);
		for(int i = 0; i >= from && i < to && i < entities.size(); i++ ) {
			outEntities.add(entities.get(i));
		}
		return entities.size();
	}
	
}
